<?php

namespace App\Http\Controllers\WebPage\Admin;

use App\Http\Models\Article;
use App\Http\Models\ArticleTag;
use App\Services\Utils\Transaction;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Libs\Bos\BosClientProxy;


class ArticleController extends Controller
{

    public function index()
    {

       $articles = Article::all()->sortByDesc('id');

       $tags = ArticleTag::where('super_tag_id',null)->get();

       return  view('web-admin.news.edit_news',compact('articles','tags'));
    }

    /**
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     */
    public function store(Request $request)
    {

        $data = $request->all();
        $data['banner'] = 'article/banner/new_banner1.png'; //兼容旧版banner图

        if ( !isset($data['content']) || $data['content'] =='')
        {
            return redirect()->back()->withInput()->withErrors('新闻内容不能为空');
        }

        $create = Transaction::handle(function () use ($data) {

            /** @var Article $created_article */
            $created_article = Article::safeCreate($data);

            $created_article->articleTags()->sync( $data['tag_ids'] );

            return $created_article;
        });


        if ( $create ) {
            return redirect()->back()->with('success','新闻： "'. $create->title .'" 添加成功');
        } else {
            return redirect()->back()->withInput()->withErrors(' 添加失败,请重试');
        }

    }

    public function edit($id)
    {
//        if ( ! session('admin_username') ) return redirect()->route('web-login');

        $article = Article::find($id);

        $article->tags = $article->articleTags->pluck('id');

        return $article;

    }

    public function update(Request $request, $id)
    {
//        if ( ! session('admin_username') ) return redirect()->route('web-login');

        $article = Article::find($id);

        $data = $request->all();

        if ( !isset($data['content']) || $data['content'] =='')
        {
            return redirect()->back()->withInput()->withErrors('新闻内容不能为空');
        }

        //TODO 这样写就根本没用到model层，不会执行model的方法,也没有过滤掉_method,_token。
//        $update = Article::where('id',$id)->update($data);

        $update = Transaction::handle(function () use ($article,$data) {

            $update_article = $article->safeUpdate($data);

            $article->articleTags()->sync( $data['tag_ids'] );

            return $update_article;
        });


        if ( $update ) {
            //todo 路由中间件不要重复使用web;
            return redirect()->to(url()->previous() . "#tab_2")->with('success','更新成功');

        } else {
            return redirect()->back()->withInput()->withErrors('更新失败,请重试');
        }

    }

    public function destroy($id)
    {

        $del = Article::destroy($id);

        if ( $del ) {
            return redirect()->to(url()->previous() . "#tab_2")->with('success','新闻删除成功');
        } else {
            return redirect()->back()->withInput()->withErrors(' 删除失败,请重试');
        }
        
    }

    public function uploadArticleImg(Request $request)
    {
        $uploadFile = $request->file('upfile');

        $img_origin_name = $uploadFile->getClientOriginalName();
        list( $img_pre , $img_ext ) = explode( "." , $img_origin_name );
        $image_key = $img_pre . time() . '.' . $img_ext ;

        $bosClient = new BosClientProxy();
        $image_path = $uploadFile->getRealPath();
        $bosClient->client->putObjectFromFile('panx-website','article/content/'.$image_key , $image_path);

        $resArr = [
            "originalName" => '',
            "name" => '',
            "url" => 'http://panx-website.gz.bcebos.com/article/content/'.$image_key,
            "size"=> 1,
            "type"=> '.' . $img_ext,
            "state"=>"SUCCESS",
        ];

        return json_encode($resArr);

    }

}

